package net.nyancofc.piconnow.tweet;

import net.arnx.jsonic.JSON;
import net.nyancofc.piconnow.data.ReverseGeoCodingResult;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.location.Location;

public class AddressManager {
	public String getAddressNameFromPosition(Location location) {
    	HttpResponse response = null;
    	String entity = "";
    	String address = "";

    	if (location == null)
    		return address;
    	if (location.getLatitude() == 0 || location.getLongitude() == 0)
    		return address;

    	try {
    		String ReverseGeoCoding = "http://www.finds.jp/ws/rgeocode.php";
            StringBuffer buff = new StringBuffer("");
            buff.append(ReverseGeoCoding).append("?json");
            buff.append("&lat=").append(Math.round(location.getLatitude()*100000)/100000.0);
            buff.append("&lon=").append(Math.round(location.getLongitude()*100000)/100000.0);
            HttpGet get = new HttpGet(buff.toString());
            DefaultHttpClient http=new DefaultHttpClient();
            response = http.execute(get);
            entity = EntityUtils.toString(response.getEntity(),"UTF-8");
        } catch (Exception e) {
        	//toast(PiconNowService.this, e.getMessage());
        }
        String jsonStr = StringEscapeUtils.unescapeJava(entity);

        ReverseGeoCodingResult result = null;
        try {
        	result = JSON.decode( jsonStr, ReverseGeoCodingResult.class );
        } catch (Exception e) {
        	e.printStackTrace();
        }
        address = result.toAddressString();
        return address;
	}

}
